package com.linkstec.util;

import java.sql.Connection;
import java.sql.SQLException;

import javax.sql.DataSource;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class BatchContext {
	private static final Logger logger = LogManager.getLogger();

	private static ThreadLocal<Connection> connStore = new ThreadLocal<Connection>();
	
	public static Connection getConnection() {
		Connection conn = connStore.get();
		if (conn == null) {
			try {
				conn = getNewConnection();
				connStore.set(conn);
			} catch(Exception ex) {
				logger.error("", ex);
			}
		}

		return conn;
	}
	
	public static void closeConnection() {
		Connection conn = connStore.get();
		connStore.set(null);

		if (conn != null) {
			try {
				conn.close();
			} catch(SQLException ex) {
				logger.error("", ex);
			}
			conn = null;
		}
	}
	
	public static void closeConnection(Connection conn) {
		if (conn != null) {
			try {
				conn.close();
			} catch(SQLException ex) {
				logger.error("", ex);
			}
			conn = null;
		}		
	}
	
	public static Connection getNewConnection() {
		try {
			DataSource ds = DataSourceUtil.getDataSource();
			
			Connection connNew = ds.getConnection();
			while (!connNew.isValid(10)) {
				connNew.close();
				connNew = null;
				
				connNew = ds.getConnection();
			}
			
			connNew.setAutoCommit(false);
			return connNew;
		} catch(Exception ex) {
			logger.error("", ex);
			throw new RuntimeException(ex.getLocalizedMessage());
		}
	}
	
	public static Connection getNewConnection(String datasource) {
		try {
			DataSource ds = DataSourceUtil.getDataSource();
			
			Connection connNew = ds.getConnection();
			while (!connNew.isValid(10)) {
				connNew.close();
				connNew = null;
				
				connNew = ds.getConnection();
			}

			connNew.setAutoCommit(false);
			return connNew;
		} catch(Exception ex) {
			logger.error("", ex);
			throw new RuntimeException(ex.getLocalizedMessage());
		}
	}
}
